<?php
/**
 * Description:
 * Author: hezhizheng
 * Date: 2018/11/14
 * Time: 17:08
 * Created by Created by Panxsoft.
 */

namespace App\Models\Manufacturer;

use App\Models\Products\Product;
use App\Services\Utils\ImageHelper;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

/**
 * Class Manufacturer
 *
 * @method static self filterProducts(?array $product_ids)
 *
 * @package App\Models
 * @mixin Builder
 */
class Manufacturer extends Model
{
    protected $guarded = [];

    protected $table = 'manufacturer';

    protected $primaryKey = 'manufacturer_id';

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function manufacturerToStores()
    {
        return $this->hasMany(ManufacturerToStore::class, 'manufacturer_id', 'manufacturer_id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function manufacturerDescriptions()
    {
        return $this->hasMany(ManufacturerDescription::class, 'manufacturer_id', 'manufacturer_id');
    }

    public function getImageAttribute()
    {
        if (!$this->attributes['image']) return null;

        return ImageHelper::generateImagePath($this->attributes['image']);
    }

    /**
     * @used-by filterProducts
     *
     * @param Builder $query
     * @param array $product_ids
     */
    public function scopeFilterProducts(Builder $query, ?array $product_ids): void
    {
        if (is_array($product_ids)) {
            $self_ids = (new Product)
                ->whereKey($product_ids)
                ->distinct() // distinct 与 groupBy($this->primaryKey) 结果一样
                ->pluck($this->primaryKey);

            $query->whereIn($this->getQualifiedKeyName(), $self_ids);
        }
    }
}